# -*- coding: utf-8 -*-
# @时间：2023/11/2 20:36
# @作者：CJiaの可乐哥
# @文件名：usual
# @软件：Pycharm2023

from django.shortcuts import get_object_or_404
from utils.cj_jwt import parse_payload
from system.models import Users, UserRole, RolePermission, UserPost


def get_user_info_from_token(request):
    token = request.META.get("HTTP_AUTHORIZATION")
    token = token.replace('Bearer ', "")
    user = parse_payload(token)
    user_obj = Users.objects.get(id=user['data']['id'], username=user['data']['username'],
                                 is_superuser=user['data']['is_superuser'])
    return user_obj


def get_user_info(id):
    user = get_object_or_404(Users, id=id)
    role_ids = UserRole.objects.filter(user_id=user.id)
    role_ids = [role_id.role_id for role_id in role_ids]
    permissions = RolePermission.objects.filter(role_id__in=role_ids).values()
    permissions = list(set([permission['permission'] for permission in permissions]))
    post_ids = UserPost.objects.filter(user_id=user.id)
    post_ids = [post_id.post_id for post_id in post_ids]
    user.roles = role_ids
    user.posts = post_ids
    user.permissions = permissions
    return user
